package com.wb.mas.ui.main;

import android.app.Application;
import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.wb.mas.R;
import com.wb.mas.app.AppApplication;
import com.wb.mas.app.Constants;
import com.wb.mas.app.DictInfoTypeKey;
import com.wb.mas.app.SPKeys;
import com.wb.mas.app.UUidUtils;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.ApproveResponse;
import com.wb.mas.entity.BannerEntity;
import com.wb.mas.entity.BannerResponse;
import com.wb.mas.entity.CalculateRateResponse;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.entity.DicInfoResponse;
import com.wb.mas.entity.IdentityInfoResponse;
import com.wb.mas.entity.JsOrderData;
import com.wb.mas.entity.ProDetailResponse;
import com.wb.mas.entity.ProdDetailEntity;
import com.wb.mas.entity.RemindInfoResponse;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.ui.auth.AuthJumpManager;
import com.wb.mas.ui.bank.BankActivity;
import com.wb.mas.ui.defer.DeferActivity;
import com.wb.mas.ui.help.HelpActivity;
import com.wb.mas.ui.login.LoginAc;
import com.wb.mas.ui.order.OrderActivity;
import com.wb.mas.ui.refund.RefundActivity;
import com.wb.mas.ui.success.SuccessActivity;
import com.wb.mas.ui.webview.WebViewActivity;
import com.wb.mas.utils.HttpsUtils;
import com.wb.mas.utils.MoneyUtils;
import com.wb.mas.utils.response.ResultException;
import com.wb.mas.utils.TimeUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.functions.Function6;
import io.reactivex.functions.Function7;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;

/**
 * Copyright (C) 2018,
 * MainViewModel
 * <p>
 * Description
 * 首页
 *
 * @author mwl
 * @version 1.0
 * <p>
 * Ver 1.0, 2019-04-29, mwl, Create file
 */
public class MainViewModel extends BaseViewModel<DemoRepository> {

    public static final String AUTH_SUC_EVENT = "auth_suc_event";


    /**
     * drawerLayout 显示隐藏
     **/
    public ObservableField<Boolean> drawerOpen = new ObservableField<>();
    /**
     * 用户头像圆形
     **/
    public ObservableField<Boolean> isCircle = new ObservableField<>();
    /**
     * 用户头像默认
     **/
    public ObservableField<Integer> iconDefaultRes = new ObservableField<>();
    /**
     * 用户头像绑定
     **/
    public ObservableField<String> iconUrl = new ObservableField<>();

    /**
     * 用户名称绑定
     **/
    public ObservableField<String> userName = new ObservableField<>();

    /**
     * Banner数据绑定
     **/
    public ObservableField<List<BannerEntity>> bannerDatas = new ObservableField<>();


    /**
     * 提示框是否显示
     **/
    public ObservableField<Boolean> isTipVisable = new ObservableField<>();


    /**
     * 提示框提示标题文字
     **/
    public ObservableField<String> tipTitle = new ObservableField<>();

    /**
     * 提示框提示内容文字
     **/
    public ObservableField<String> tipContent = new ObservableField<>();

    /**
     * 提示框最后还款是否显示
     **/
    public ObservableField<Boolean> isTipLastFundDate = new ObservableField<>();

    /**
     * 提示框最后还款内容
     **/
    public ObservableField<String> tipLastFundDate = new ObservableField<>();

    /**
     * 提示框逾期天数是否显示
     **/
    public ObservableField<Boolean> isTipOverdueDate = new ObservableField<>();

    /**
     * 提示框逾期天数显示内容
     **/
    public ObservableField<String> tipOverdueDate = new ObservableField<>();


    /**
     * 提示框红色按钮文字
     **/
    public ObservableField<String> redBtnText = new ObservableField<>();

    /**
     * 提示框白色按钮是否显示
     **/
    public ObservableField<Boolean> isWhiteBtnShow = new ObservableField<>();

    /**
     * 选择借款金额内容
     **/
    public ObservableField<String> borrowMoney = new ObservableField<>();

    /**
     * 选择借款期限内容
     **/
    public ObservableField<String> borrowDate = new ObservableField<>();


    /**
     * 实际到账金额内容
     **/
    public ObservableField<String> realMoney = new ObservableField<>();

    /**
     * 到期应还内容
     **/
    public ObservableField<String> refundMoney = new ObservableField<>();

    /**
     * 还款日期内容
     **/
    public ObservableField<String> refundDate = new ObservableField<>();

    /**
     * 想要借款金额内容
     **/
    public ObservableField<String> wantBorrow = new ObservableField<>();
    public ObservableField<String> wantBorrowCode = new ObservableField<>();

    /**
     * 借款用途内容
     **/
    public ObservableField<String> borrowUse = new ObservableField<>();
    public ObservableField<String> borrowUseCode = new ObservableField<>();


    /**
     * checkbox是否选中
     **/
    public ObservableField<Boolean> checked = new ObservableField<>();

    /**
     * 提交按钮的是否可用
     **/
    public ObservableField<Boolean> isCommitEnable = new ObservableField<>();


    /**
     * banner数据
     */
//    public List<BannerEntity> bannerEntities;

    /**
     * 首页借款金额数据
     */
    public List<ProdDetailEntity> prodDetailEntities;

    /**
     * 未还款订单数据
     */
//    public OrderEntity orderEntity;

    /**
     * 想要借款金额数据字典
     */
    public List<DicInfoEntity> needMoneyList;

    /**
     * 借款用途数据字典
     */
    public List<DicInfoEntity> usageOfLoanList;

    /**
     * 有资料回退数据
     */
//    public BackStatusResponse.DataBean backDataBean;
    public RemindInfoResponse.DataBean reminDataDean;

    /**
     * 资料认证数据
     */
    public ApproveResponse.DataBean approveDataBean;

    /**
     * 计算利率数据
     */
    public CalculateRateResponse.DataBean calculateDateBean;

    /**
     * 借款金额选择项目
     */
    public int borrowMoneyIndex;

    /**
     * 借款时间选择项目
     */
    public int borrowDateIndex;

    /**
     * 想要借款金额选择
     */
    public int wantBorrowIndex;

    /**
     * 借款用途选择
     */
    public int borrowUseIndex;

    public Location location;

    public UiChangeEvent uc = new UiChangeEvent();


    public MainViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);

        Messenger.getDefault().register(this, MainViewModel.AUTH_SUC_EVENT, String.class, new BindingConsumer<String>() {
            @Override
            public void call(String s) {
                getInitDatas();
            }

        });
    }


    @Override
    public void onCreate() {
        super.onCreate();
        isCircle.set(true);
        iconDefaultRes.set(R.mipmap.ma_icon_default);
        getInitDatas();
    }


    public class UiChangeEvent {
        public SingleLiveEvent borrowMoneyEvent = new SingleLiveEvent();
        public SingleLiveEvent borrowDateEvent = new SingleLiveEvent();
        public SingleLiveEvent wantBorrowMoneyEvent = new SingleLiveEvent();
        public SingleLiveEvent borrowUseEvent = new SingleLiveEvent();
        public SingleLiveEvent commitEvent = new SingleLiveEvent();
        public SingleLiveEvent reqOrderEvent = new SingleLiveEvent();
    }


    /**
     * 借款中的订单点击事件
     */
    public BindingCommand navBorrowOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putInt("type", OrderActivity.ORDER_BORROW);
            startActivity(OrderActivity.class, bundle);
        }
    });


    /**
     * 完成的订单点击事件
     */
    public BindingCommand navCompleteOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putInt("type", OrderActivity.ORDER_COMPLETE);
            startActivity(OrderActivity.class, bundle);
//
        }
    });


    /**
     * 我的银行卡点击事件
     */
    public BindingCommand navBankOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            startActivity(BankActivity.class);
        }
    });


    /**
     * 帮助中心点击事件
     */
    public BindingCommand navHelpOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            startActivity(HelpActivity.class);

        }
    });

    /**
     * 关于我们点击事件
     */
    public BindingCommand navAboutOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Bundle bundle = new Bundle();
            bundle.putString("title", getString(R.string.about_title));
            bundle.putString("url", Constants.ABOUT_US_URL);
            startActivity(WebViewActivity.class, bundle);
//            startActivity(AboutActivity.class);

        }
    });

    /**
     * 退出登录点击事件
     */
    public BindingCommand navLogoutOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            SPUtils.getInstance().remove(SPKeys.KEY_OF_TOKEN);
            SPUtils.getInstance().remove(SPKeys.SP_ADDRESSBOOKUUID);
            SPUtils.getInstance().remove(SPKeys.SP_USERUUID);
            SPUtils.getInstance().remove(SPKeys.SP_BACK_USERUUID);
            startActivity(LoginAc.class);
        }
    });

    /**
     * icon的点击事件
     */
    public BindingCommand iconOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            drawerOpen.set(true);
        }
    });


    /**
     * 借款协议的点击事件
     */
    public BindingCommand agreeOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putString("title", getString(R.string.main_agree_title));
            bundle.putString("url", Constants.AGREE_URL);
            Log.e("-----", Constants.AGREE_URL);
            JsOrderData jsOrderData = new JsOrderData(com.blankj.utilcode.util.SPUtils.getInstance().getString(SPKeys.KEY_OF_TOKEN), prodDetailEntities.get(borrowMoneyIndex).prodRange, prodDetailEntities.get(borrowMoneyIndex).prodDetailDTOList.get(borrowDateIndex).pTerm);
            bundle.putSerializable("orderData", jsOrderData);
            startActivity(WebViewActivity.class, bundle);
        }
    });


    /**
     * icon的点击事件
     */
    public BindingCommand iconCloseCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            drawerOpen.set(false);
        }
    });

    /**
     * banner的点击事件
     */
    public BindingCommand goBannerOnClickCommand = new BindingCommand(new BindingConsumer<Integer>() {
        @Override
        public void call(Integer poi) {

//            ToastUtils.showShort("dianjil---" + poi);
        }
    });


    /**
     * 红色按钮点击事件
     */
    public BindingCommand redBtnOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            if (getString(R.string.main_refund).equals(redBtnText.get())) {
                Bundle bundle = new Bundle();
                bundle.putString("orderId", reminDataDean.getOrderId());
                bundle.putString("approvedAmt", reminDataDean.getRepayAmt());
                bundle.putInt("type", RefundActivity.TYPE_REFUND);
                startActivity(RefundActivity.class, bundle);
            } else {
                if (RemindInfoResponse.DataBean.CODE_BACK.equals(reminDataDean.code)) {
                    AuthJumpManager.goToNextPage(reminDataDean.authPageCode);
                } else if (RemindInfoResponse.DataBean.CODE_BANK.equals(reminDataDean.code)) {
                    AuthJumpManager.goToNextPage(Constants.AUTH_PAGE_CODE_BANK_INFO_CODE);
                }

            }


        }
    });


    /**
     * 白色按钮点击事件
     */
    public BindingCommand whiteBtnOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            Bundle bundle = new Bundle();
            bundle.putString("orderId", reminDataDean.getOrderId());
            startActivity(DeferActivity.class, bundle);
        }
    });


    /**
     * 选择借款金额按钮点击事件
     */
    public BindingCommand selectBorrowMoneyOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            uc.borrowMoneyEvent.setValue(new Object());

        }
    });

    /**
     * 选择借款期限按钮点击事件
     */
    public BindingCommand selectBorrowDateOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            uc.borrowDateEvent.setValue(new Object());

        }
    });

    /**
     * 想要借款金额按钮点击事件
     */
    public BindingCommand wantBorrowDateOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            uc.wantBorrowMoneyEvent.setValue(new Object());

        }
    });

    /**
     * 借款用途按钮点击事件
     */
    public BindingCommand borrowUseDateOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
            uc.borrowUseEvent.setValue(new Object());

        }
    });

    /**
     * Checkbox选中事件
     */
    public BindingCommand checkBoxCheckListerCommand = new BindingCommand(new BindingConsumer<Boolean>() {
        @Override
        public void call(Boolean b) {
            if (isGoLogin()) {
                return;
            }
            checked.set(b);
            refushCommitEnable();
//            startActivity(AuthIdAc.class);
//            startActivity(AuthContactAc.class);
//            startActivity(AuthWorkInfoAc.class);
//            startActivity(AuthPersonalInfoAc.class);
//            startActivity(AuthBankCardAc.class);
//            startActivity(AuthWorkInfoAc.class);
//            startActivity(AuthExtraAc.class);
//            startActivity(LoginByPhoneAc.class);
        }
    });


    /**
     * 提交按钮点击事件
     */
    public BindingCommand commitOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if (isGoLogin()) {
                return;
            }
//            Intent authIntent = new Intent(getApplication(), LoginAc.class);
//            Intent authIntent = new Intent(getApplication(), AuthIdAc.class);
////            Intent authIntent = new Intent(getApplication().getApplicationContext(), AuthPersonalInfoAc.class);
////            Intent authIntent = new Intent(getApplication(), AuthWorkInfoAc.class);
////            Intent authIntent = new Intent(getApplication(), AuthContactAc.class);
////            Intent authIntent = new Intent(getApplication(), AuthBankCardAc.class);
////            Intent authIntent = new Intent(getApplication(), AuthExtraAc.class);
//
//            getApplication().getApplicationContext().startActivity(authIntent);
////            startActivity(AuthPersonalInfoAc.class);
//            startActivity(AuthContactAc.class);
            uc.reqOrderEvent.setValue(new Object());


        }
    });


    /**
     * 借款金额被选中
     *
     * @param position
     */
    public void setBorrowMoneySelect(int position) {
        borrowMoneyIndex = position;
        borrowDateIndex = 0;
        borrowMoney.set(MoneyUtils.formatShow(prodDetailEntities.get(borrowDateIndex).prodRange));
        borrowDate.set("");
        realMoney.set("");
        refundMoney.set("");
        refundDate.set("");
        refushCommitEnable();
    }

    /**
     * 借款期限被选中
     *
     * @param position
     */
    public void setBorrowDateSelect(int position) {
        realMoney.set("");
        refundMoney.set("");
        refundDate.set("");
        borrowDateIndex = position;
        borrowDate.set(prodDetailEntities.get(borrowMoneyIndex).prodDetailDTOList.get(position).pTerm);
        refushCommitEnable();
        calculate();
    }

    /**
     * 想要借款被选中
     *
     * @param position
     */
    public void setWantBorrowSelect(int position) {
        wantBorrowIndex = position;
        wantBorrow.set(needMoneyList.get(position).dictValue);
        wantBorrowCode.set(needMoneyList.get(position).dictCode);
        refushCommitEnable();
    }

    /**
     * 借款用途被选中
     *
     * @param position
     */
    public void setBorrowUseSelect(int position) {
        borrowUseIndex = position;
        borrowUse.set(usageOfLoanList.get(position).dictValue);
        borrowUseCode.set(usageOfLoanList.get(position).dictCode);
        refushCommitEnable();
    }


    /**
     * 刷新按钮的是否可点击
     */
    private void refushCommitEnable() {
        if (!TextUtils.isEmpty(borrowMoney.get()) && !TextUtils.isEmpty(borrowDate.get()) && !TextUtils.isEmpty(wantBorrow.get()) && !TextUtils.isEmpty(borrowUse.get()) && checked.get() != null && checked.get()) {
            isCommitEnable.set(true);
        } else {
            isCommitEnable.set(false);
        }

    }


    private void getNoLoginDatas() {
        userName.set(getString(R.string.main_nologin));
//        showDialog();
//        addSubscribe(model.getBanner(new HashMap<String, Object>())
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<BannerResponse>() {
//                    @Override
//                    public void accept(BannerResponse bannerResponse) throws Exception {
//                        dismissDialog();
//                        bannerEntities = bannerResponse.getData();
//                        if (bannerEntities != null) {
//                            bannerDatas.set(bannerEntities);
//                        }
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        dismissDialog();
//                        ToastUtils.showShort(throwable.getMessage());
//                    }
//                }));

    }


    private void getInitDatas() {
        userName.set("");
        if (TextUtils.isEmpty(SPUtils.getInstance().getString(SPKeys.KEY_OF_TOKEN))) {
            getNoLoginDatas();
            return;
        }
//        Observable<BannerResponse> bannerResponseObservable = model.getBanner(new HashMap<String, Object>()).subscribeOn(Schedulers.io());
        Observable<ProDetailResponse> proDetailResponseObservable = model.getProdDeailList(new HashMap<String, Object>()).subscribeOn(Schedulers.io());

//        Map<String, Object> orderParams = new HashMap<>();
//        orderParams.put("type", "110");
//        Observable<OrderResponse> orderResponseObservable = model.getOrderInfoList(orderParams).subscribeOn(Schedulers.io());

        Observable<RemindInfoResponse> remidResponseObservable = model.getRemindInfo(new HashMap<String, Object>()).subscribeOn(Schedulers.io());


        Map<String, Object> needMoneyParams = new HashMap<>();
        needMoneyParams.put("dictType", DictInfoTypeKey.need_money);
        Observable<DicInfoResponse> needMoneyResponse = model.getDicInfo(needMoneyParams).subscribeOn(Schedulers.io());

        Map<String, Object> usageOfLoanParams = new HashMap<>();
        usageOfLoanParams.put("dictType", DictInfoTypeKey.usage_of_loan);
        Observable<DicInfoResponse> usageOfLoanResponse = model.getDicInfo(usageOfLoanParams).subscribeOn(Schedulers.io());

        Observable<RootApiBean> isDeferResponse = model.rolloverApp(new HashMap<String, Object>()).subscribeOn(Schedulers.io());

//        Observable<BackStatusResponse> backResponse = model.getBackStatus(new HashMap<String, Object>()).subscribeOn(Schedulers.io());

        Observable<ApproveResponse> responseObservable = model.getApproveStatus(new HashMap<String, Object>()).subscribeOn(Schedulers.io());
        showDialog();
        addSubscribe(
                Observable.zip( proDetailResponseObservable, responseObservable, remidResponseObservable, needMoneyResponse, usageOfLoanResponse, isDeferResponse,new Function6< ProDetailResponse, ApproveResponse, RemindInfoResponse, DicInfoResponse, DicInfoResponse, RootApiBean, Object>() {

                    @Override
                    public Object apply( ProDetailResponse proDetailResponse, ApproveResponse approveResponse, RemindInfoResponse remindInfoResponse, DicInfoResponse dicInfoResponse, DicInfoResponse dicInfoResponse2, RootApiBean isDeferBean) throws Exception {
//                        bannerEntities = bannerResponse.getData();
                        prodDetailEntities = proDetailResponse.getData();
                        if (remindInfoResponse != null && remindInfoResponse.getData() != null) {
                            reminDataDean = remindInfoResponse.getData();
                        } else {
                            reminDataDean = null;
                        }
                        needMoneyList = dicInfoResponse.getData();
                        usageOfLoanList = dicInfoResponse2.getData();
                        SPUtils.getInstance().put(SPKeys.SP_ISDEFER, isDeferBean.isRel());

                        if (approveResponse != null && approveResponse.getData() != null) {
                            approveDataBean = approveResponse.getData();
                        }
                        return new Object();
                    }


                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Object>() {
                            @Override
                            public void accept(Object o) throws Exception {
                                dismissDialog();
                                setDatas();
                                getUserInfo();
                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                dismissDialog();
                                throwable.printStackTrace();
                                Log.e("-------", throwable.getMessage());
                                ToastUtils.showShort(throwable.getMessage());
                            }
                        })
        );
    }

    private void getUserInfo() {
        Map<String, Object> maps = new HashMap<>();
        List<String> stringList = new ArrayList<>();
        addSubscribe(model.getIdentityInfo(maps)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<IdentityInfoResponse>() {
                    @Override
                    public void accept(IdentityInfoResponse infoResponse) throws Exception {
                        if (infoResponse != null && infoResponse.getData() != null) {

                            String phoneNum = infoResponse.getData().userName;
                            phoneNum = phoneNum.replaceAll("(\\d{4})\\d{4}(\\d{4})", "$1****$2");
                            userName.set(phoneNum);
                        } else {
                            userName.set("");
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        ToastUtils.showShort(throwable.getMessage());
                    }
                }));


    }


    private void setDatas() {
//        if (bannerEntities != null) {
//            bannerDatas.set(bannerEntities);
//        }
        if (reminDataDean != null && !TextUtils.isEmpty(reminDataDean.userUUID)) {
            SPUtils.getInstance().put(SPKeys.SP_BACK_USERUUID, reminDataDean.userUUID);
        } else {
            SPUtils.getInstance().put(SPKeys.SP_BACK_USERUUID, "");
        }
        refushApproveDataBean();
        SPUtils.getInstance().put(SPKeys.SP_ISBACK, false);

        if (reminDataDean != null) {
            if (RemindInfoResponse.DataBean.CODE_BACK.equals(reminDataDean.code)) {
                //资料回退
                SPUtils.getInstance().put(SPKeys.SP_ISBACK, true);
                isTipVisable.set(true);
                tipTitle.set(getString(R.string.main_error_data));
                tipContent.set(reminDataDean.orderBackReason);
                SPUtils.getInstance().put(SPKeys.SP_NOAUTH_STEP, reminDataDean.authPageCode);
                isTipLastFundDate.set(false);
                isTipOverdueDate.set(false);
                isWhiteBtnShow.set(false);
                redBtnText.set(getString(R.string.main_approve));
            } else if (RemindInfoResponse.DataBean.CODE_BANK.equals(reminDataDean.code)) {
                SPUtils.getInstance().put(SPKeys.SP_ISBACK, true);
                isTipVisable.set(true);
                tipTitle.set(getString(R.string.main_error_info));
                tipContent.set(getString(R.string.main_error_bank));
                SPUtils.getInstance().put(SPKeys.SP_NOAUTH_STEP, Constants.AUTH_PAGE_CODE_BANK_INFO_CODE);
                isTipLastFundDate.set(false);
                isTipOverdueDate.set(false);
                isWhiteBtnShow.set(false);
                redBtnText.set(getString(R.string.main_approve));
            } else if (RemindInfoResponse.DataBean.CODE_ORDER_REFUND.equals(reminDataDean.code)) {
                isTipVisable.set(true);
                tipTitle.set(getString(R.string.main_wait_refund_money));
                tipContent.set(MoneyUtils.formatShow(reminDataDean.repayAmt));
                isTipLastFundDate.set(true);
                tipLastFundDate.set(getString(R.string.main_last_refund_date, reminDataDean.repayDate));
                isTipOverdueDate.set(false);
                redBtnText.set(getString(R.string.main_refund));
                isWhiteBtnShow.set(SPUtils.getInstance().getBoolean(SPKeys.SP_ISDEFER, false));
            } else if (RemindInfoResponse.DataBean.CODE_ORDER_DUE.equals(reminDataDean.code)) {
                isTipVisable.set(true);
                tipTitle.set(getString(R.string.main_wait_refund_money));
                tipContent.set(MoneyUtils.formatShow(reminDataDean.repayAmt));
                isTipLastFundDate.set(true);
                tipLastFundDate.set(getString(R.string.main_last_refund_date, reminDataDean.repayDate));
                isTipOverdueDate.set(true);
                tipOverdueDate.set(getString(R.string.main_overdue_date, reminDataDean.overdueDay));
                redBtnText.set(getString(R.string.main_refund));
                isWhiteBtnShow.set(SPUtils.getInstance().getBoolean(SPKeys.SP_ISDEFER, false));
            } else {
                isTipVisable.set(false);
            }

        } else {
            isTipVisable.set(false);
        }
        if (prodDetailEntities != null && prodDetailEntities.size() > 0 && prodDetailEntities.get(0).prodDetailDTOList != null && prodDetailEntities.get(0).prodDetailDTOList.size() > 0) {
            setBorrowMoneySelect(0);
            setBorrowDateSelect(0);
        }
    }

    private void refushApproveDataBean() {
        if (approveDataBean != null) {
            if (!TextUtils.isEmpty(approveDataBean.userUuid)) {
                SPUtils.getInstance().put(SPKeys.SP_USERUUID, approveDataBean.userUuid);
            }

            if (!TextUtils.isEmpty(approveDataBean.addressBookUuid)) {
                SPUtils.getInstance().put(SPKeys.SP_ADDRESSBOOKUUID, approveDataBean.addressBookUuid);
            }

            if (approveDataBean.notCodes != null && approveDataBean.notCodes.size() != 0) {
                SPUtils.getInstance().put(SPKeys.SP_NOAUTH_STEP, listToString(approveDataBean.notCodes, ","));
            } else {
                SPUtils.getInstance().put(SPKeys.SP_NOAUTH_STEP, "");
            }
        }

    }


    /**
     * 计算费率的请求
     */
    private void calculate() {
        Map<String, Object> maps = new HashMap<>();
        maps.put("borrowMoney", prodDetailEntities.get(borrowMoneyIndex).prodRange);
        maps.put("pId", prodDetailEntities.get(borrowMoneyIndex).prodDetailDTOList.get(borrowDateIndex).pId);
        showDialog();
        addSubscribe(model.calculateRate(maps)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<CalculateRateResponse>() {
                    @Override
                    public void accept(CalculateRateResponse calculateRateResponse) throws Exception {
                        dismissDialog();
                        if (HttpsUtils.isResponseStatusCur(calculateRateResponse)) {
                            if (calculateRateResponse.getData() != null) {
                                calculateDateBean = calculateRateResponse.getData();
                                realMoney.set(getString(R.string.money) + " " + MoneyUtils.formatShow(calculateRateResponse.getData().neteceipts));
                                refundMoney.set(getString(R.string.money) + " " + MoneyUtils.formatShow(calculateRateResponse.getData().expiryReturned));
                                refundDate.set(TimeUtils.getAfterNowDay(Integer.parseInt(calculateRateResponse.getData().pTerm)));
                            } else {
                                calculateDateBean = null;
                            }
                        } else {
                            calculateDateBean = null;
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        ToastUtils.showShort(throwable.getMessage());

                    }
                }));

    }


    /**
     * 请求订单
     */
    public void reqOrder() {
        // TODO: 2019-05-20 如果该步骤资料被回退，有流程卡主的风险
        if (reminDataDean != null && (RemindInfoResponse.DataBean.CODE_BACK.equals(reminDataDean.code) || RemindInfoResponse.DataBean.CODE_BANK.equals(reminDataDean.code))) {
            ToastUtils.showShort(R.string.main_go_approve);
            return;
        }
        showDialog();
        final Observable<ApproveResponse> approveObservable = model.getApproveStatus(new HashMap<String, Object>()).subscribeOn(Schedulers.io());


        HashMap<String, Object> authParams = new HashMap<String, Object>();
        authParams.put("needMoney", wantBorrowCode.get());
        authParams.put("moneyTodo", borrowUseCode.get());
        authParams.put("authPageCode", "borrowing_needs_code");
        authParams.put("userUuid", "");
        authParams.put("addressBookUuid", "");

//        addSubscribe(model.checkOrderQualifications(new HashMap<String, Object>())
        addSubscribe(model.saveOrUpdateCustomerInfo(authParams)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .flatMap(new Function<RootApiBean, ObservableSource<RootApiBean>>() {
                            @Override
                            public ObservableSource<RootApiBean> apply(RootApiBean rootApiBean) throws Exception {
                                if (HttpsUtils.isResponseStatusCur(rootApiBean)) {
                                    return model.checkOrderQualifications(new HashMap<String, Object>()).subscribeOn(Schedulers.io());
                                } else {
                                    ToastUtils.showShort(rootApiBean.getMessage());
                                    return null;
                                }

                            }
                        })
                        .flatMap(new Function<RootApiBean, ObservableSource<ApproveResponse>>() {
                            @Override
                            public ObservableSource<ApproveResponse> apply(RootApiBean rootApiBean) throws Exception {
                                if (HttpsUtils.isResponseStatusCur(rootApiBean)) {
                                    if (rootApiBean.isRel()) {
                                        return approveObservable;
                                    } else {
                                        ToastUtils.showShort(getString(R.string.main_noorder_denied));
                                        return null;
                                    }
                                } else {
                                    return null;
                                }

                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .flatMap(new Function<ApproveResponse, ObservableSource<RootApiBean>>() {
                            @Override
                            public ObservableSource<RootApiBean> apply(ApproveResponse approveResponse) throws Exception {
                                if (HttpsUtils.isResponseStatusCur(approveResponse)) {
                                    if (approveResponse.isRel() && approveResponse.getData() != null) {
                                        approveDataBean = approveResponse.getData();
                                        refushApproveDataBean();
                                        if (approveDataBean.status == 1) {
                                            if (approveDataBean.notCodes != null && approveDataBean.notCodes.size() > 0) {
                                                AuthJumpManager.goToNextPage(approveDataBean.notCodes.get(0));
                                            } else {
                                                ToastUtils.showShort(R.string.main_noorder_replay);
                                            }
                                            return null;
                                        } else {
                                            HashMap<String, Object> map = new HashMap<>();
                                            map.put("expiryReturned", calculateDateBean.applyAmt);
                                            map.put("pId", prodDetailEntities.get(borrowMoneyIndex).prodDetailDTOList.get(borrowDateIndex).pId);
                                            return model.createOrder(map).subscribeOn(Schedulers.io());
                                        }
                                    } else {
                                        ToastUtils.showShort(R.string.main_noorder_replay);
                                        return null;
                                    }
                                } else {
                                    return null;
                                }

                            }
                        })
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<RootApiBean>() {
                            @Override
                            public void accept(RootApiBean rootApiBean) throws Exception {
                                dismissDialog();
                                if (HttpsUtils.isResponseStatusCur(rootApiBean)) {
                                    if (rootApiBean != null && rootApiBean.isRel()) {
//                                ToastUtils.showShort(R.string.main_order_wait);
                                        uc.commitEvent.setValue(new Object());
                                        Bundle bundle = new Bundle();
                                        bundle.putInt("type", SuccessActivity.TYPE_BORROW);
                                        startActivity(SuccessActivity.class, bundle);
                                    } else {
                                        ToastUtils.showShort(R.string.main_noorder_replay);
                                    }
                                }

                            }
                        }, new Consumer<Throwable>() {
                            @Override
                            public void accept(Throwable throwable) throws Exception {
                                dismissDialog();
                                if (throwable instanceof ResultException) {
                                    ToastUtils.showShort(throwable.getMessage());
                                }
                            }
                        })
        );
    }

    /**
     * 上传定位和通讯录数据
     */
    public void uploadData(String path) {

        if (location != null) {
            TelephonyManager phoneMgr = (TelephonyManager) AppApplication.getActivityContext().getSystemService(Context.TELEPHONY_SERVICE);
            String phoneNum = phoneMgr.getLine1Number(); //获取到手机号
            Map<String, Object> locatMap = new HashMap<>();
            locatMap.put("longitude", String.valueOf(location.getLongitude()));
            locatMap.put("latitude", String.valueOf(location.getLatitude()));
            locatMap.put("saveType", "2");
            locatMap.put("userPhone", phoneNum);
            addSubscribe(model.saveLngLat(locatMap)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Consumer<RootApiBean>() {
                        @Override
                        public void accept(RootApiBean rootApiBean) throws Exception {
                        }
                    }, new Consumer<Throwable>() {
                        @Override
                        public void accept(Throwable throwable) throws Exception {
                        }
                    })
            );

        } else {
        }


        Map<String, Object> map = new HashMap<>();
        map.put("pullData", TimeUtils.getNowDate());
        map.put("userUuid", UUidUtils.getAddressBookUuid());
        map.put("pullUserDataType", "3");

        addSubscribe(model.uploadPhone(map, new File(path))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean rootApiBean) throws Exception {

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                })
        );


    }


    public static String listToString(List list, String separator) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
            if (i < list.size() - 1) {
                sb.append(separator);
            }
        }
        return sb.toString();
    }

    private boolean isGoLogin() {
        if (TextUtils.isEmpty(SPUtils.getInstance().getString(SPKeys.KEY_OF_TOKEN))) {
            startActivity(LoginAc.class);
            return true;
        }
        return false;
    }


}
